<?php

namespace App\Http\Controllers;

use App\Article;
use App\Facades\Qcloud\Facade\Qcloud;
use Illuminate\Http\Request;
use App\ArticleCategory;

class ArticleCategoryController extends Controller
{
    public function _list(Request $request){
        $cond = [];
        $search_data = [];
        if($request->filled('name')){
            $cond[] = ['name','like','%'.$request->name.'%'];
            $search_data['name'] = $request->name;
        }
        $list = $this->getList(ArticleCategory::where($cond)->orderBy('sort','asc')->get(), 0, 0);//所有分类列表
        return view('ArticleCategory.list',[
            'list' => $list,
            'search_data' => $search_data
        ]);
    }

    public function edit(Request $request){
        $id = $request->filled('id') ? $request->id : null;
        if($id==9999){
            return json_encode([
                'code' => 0,
                'msg' => '[default] article_category can not be edited!'
            ]);
        }

        if(!$_POST){
            $cats = $this->getList(ArticleCategory::orderBy('sort','asc')->get(), 0, 0);//所有分类列表
            $info = ArticleCategory::find($id);
            return view('ArticleCategory.edit', [
                'cats' => $cats,
                'info' => $info
            ]);
        }

        $name = $request->filled('name') ? $request->name : null;
        $remark = $request->filled('remark') ? $request->remark : null;
        $pid = $request->filled('pid') ? $request->pid : null;
        $sort = $request->filled('sort') ? $request->sort : 100;//默认排序100
        $is_show = $request->filled('is_show') ? $request->is_show : 1;//默认展示1
        $logo = $request->filled('logo') ? $request->logo : '';

        if($id){
            //update
            ArticleCategory::where('id', $id)->update([
                'name' => $name,
                'remark' => $remark,
                'pid' => $pid,
                'sort' => $sort,
                'is_show' => $is_show,
                'logo' => $logo
            ]);
        }else{
            //add
            $article_category = new ArticleCategory;
            $article_category->name = $name;
            $article_category->remark = $remark;
            $article_category->pid = $pid;
            $article_category->sort = $sort;
            $article_category->is_show = $is_show;
            $article_category->logo = $logo;
            $article_category->save();
        }

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    public function del(Request $request){
        $id = $request->filled('id') ? $request->id : null;

        if($id==9999){
            return json_encode([
                'code' => 0,
                'msg' => '[default] article_category can not be deleted!'
            ]);
        }

        if(!$id)
            return json_encode([
                'code' => 0,
                'msg' => 'id can not be null'
            ]);

        $id_arr = explode(',', $id);
        foreach($id_arr as $v){
            //删除该分类
            ArticleCategory::destroy($v);
            //把子分类自动归为默认渠道
            ArticleCategory::where('pid', $v)->update(['pid'=>9999]);
            //把文章类型  修改为  默认
            Article::where('cat_id', $v)->update(['cat_id'=>9999]);
        }

        return json_encode([
            'code' => 1,
            'msg' => 'success'
        ]);
    }

    //获取分类列表(递归算法)

    /**
     * @param $data 原始数据
     * @param $pid 起始父级ID(默认是0)
     * @return array 返回【树】形表
     */
    public function getTree($data, $pid){
        $tree = [];
        foreach($data as $v){
            if($v->pid == $pid){
                $subTree = $this->getTree($data, $v->id);
                if(!empty($subTree)){
                    $tree[] = ['id'=>$v->id,'name'=>$v->name,'url'=>$v->url,'subMenu'=>$subTree];
                }else{
                    $tree[] = ['id'=>$v->id,'name'=>$v->name,'url'=>$v->url];
                }
            }
        }
        return $tree;
    }

    /**
     * @param $data 原始数据
     * @param $pid 起始父级ID(默认是0)
     * @param $depth 目录深度(默认是1)
     * @return array 返回列表（带层级数）
     */
    public function getList($data, $pid, $depth){
        static $list = [];//最终存放结果的集合，
        foreach($data as $v){
            if($v->pid == $pid){
                $v->depth = $depth;//给元素对象添加depth元素
                $list[] = $v;
                $this->getList($data, $v->id, $depth+1);
            }
        }
        return $list;
    }

    public function uploadImg(Request $request){
        if($request->hasFile('upload_logo') && $request->file('upload_logo')->isValid()){
            $img_url = QclouduUpload(md5(uniqid(md5(microtime(true)),true)), $request->file('upload_logo')->getRealPath());
            return json_encode([
                'code' => 1,
                'msg' => 'success',
                'img_url' => $img_url
            ]);
//            $ext = $request->upload_logo->extension();
//            $file_name = $this->randomKey(12).".".$ext;
//            $base_dir = '/picture/'.date('Ymd').'/';
//            $full_path = public_path() . $base_dir;
//
//            if (!file_exists($full_path)){
//                mkdir($full_path,0777,true);
//            }
//            file_put_contents(
//                $full_path . $file_name,
//                file_get_contents($request->file('upload_logo')->getRealPath())
//            );
//            return json_encode([
//                'code' => 1,
//                'msg' => 'success',
//                'img_url' => $base_dir . $file_name
//            ]);
        }else{
            return json_encode([
                'code' => 0,
                'msg' => 'Upload error,please try again'
            ]);
        }
    }

    public function randomKey($length){
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key = '';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,61)};    //生成php随机数
        }
        return $key;
    }

    //=====================================
    //          [API  Function]
    //=====================================

    public function getMenuList(Request $request){
        $list = ArticleCategory::where([
            ['is_show','=',1]
        ])->orderBy('sort','asc')->get();
        $data = [];
        foreach ($list as $v){
            $data[] = [
                'id' => $v->id,
                'name' => $v->name,
                'logo' => $v->logo ? $v->logo : '',
            ];
        }
        return json_encode([
            'code' => 1,
            'data' => $data
        ]);
    }

}
